package com.crazy.rabbitmq.mq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class GlobalEventListener {

	private static Logger logger = LoggerFactory.getLogger(MqListener.class);

    @Value("${queue.global}")
	private String queue;
    
    @Value("${exchange.global}")
	private String exchange;
    
    @Bean
    public Queue queue() {
        return new Queue(queue, true);
    }

    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange(exchange, true, false);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(fanoutExchange());
    }

    @Bean("globalContainer")
    public SimpleMessageListenerContainer globalContainer(@Qualifier("globalConnectionFactory") ConnectionFactory connectionFactory) {
    	logger.info("[接收MQ消息]start----------------------");
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueues(queue());
        container.setExposeListenerChannel(true);
        container.setConcurrentConsumers(6);
        container.setMaxConcurrentConsumers(20);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); // 设置确认模式手工确认
        container.setMessageListener((ChannelAwareMessageListener) (message, channel) -> {
            try {
                String body = new String(message.getBody());
                logger.info("[1---接收MQ消息]内容如下:" + body);
            } catch (Exception e) {
            	logger.error("[接收MQ消息]异常", e);
            } finally {
            	logger.info("[接收MQ消息]end----------------------" );
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); // 确认消息成功消费
            }
        });
        return container;
    }
}
